
import { defineStore } from "pinia";
import { ref } from 'vue';
import { loginAPI, mockLoginAPI } from "@/api/profile";

export const useProfileStore = defineStore('profile', () => {
  const userInfo = ref({})

  const onLogin = async (e) => {
    const { iv, encryptedData } = e.detail;
    const { code } = await uni.login();

    const res = await loginAPI({ iv, encryptedData, code });
    uni.showToast({ title: "登录成功" });
    userInfo.value = res.result
    uni.switchTab({ url: "/pages/index/index" });
  };

  const onMockLogin = async () => {
    const res = await mockLoginAPI();

    uni.showToast({ title: "登录成功" });
    userInfo.value = res.result
    setTimeout(() => {

      uni.switchTab({ url: "/pages/index/index" });
    }, 1500);
  };

  return { userInfo, onLogin, onMockLogin }

}, {
  persist: {
    storage: {
      getItem(key) {
        return uni.getStorageSync(key)
      },
      setItem(key, value) {
        uni.setStorageSync(key, value)
      },
    },
  }
})
